import { Forbbiden, } from "@/core/HttpException";
import { RedisCache } from "@/util/common";
import { Middleware, IMiddleware, Inject } from "@midwayjs/core";
import { NextFunction, Context } from "@midwayjs/koa";

@Middleware()
export class ForbidioMiddleware implements IMiddleware<Context, NextFunction> {

    @Inject()
    redis: RedisCache

    resolve() {
        return async (ctx: Context, next: NextFunction) => {
            // 获取redis缓存过滤接口
            const BlackIPList = await this.redis.get("client1", "sys_black:sys.login.blackEnabled")
            let ipList: any[] = []
            let blackMsg = {}
            for (const key in BlackIPList) {
                if (Object.prototype.hasOwnProperty.call(BlackIPList, key)) {
                    ipList.push(new RegExp(BlackIPList[key].ipPath))
                    blackMsg[BlackIPList[key].ipPath] = {
                        fkMsg: "您已被拉黑！",
                        blackIp: BlackIPList[key].ipPath,
                        pushDate: BlackIPList[key].pushDate,
                        expiryDate: BlackIPList[key].expiryDate,
                        remark: BlackIPList[key].remark
                    }
                }
            }
            // 判断接口放行
            if (ipList.findIndex(v => v.test(ctx.request.ip)) !== -1) {
                throw new Forbbiden(blackMsg[ctx.request.ip])
            }
            await next()
        }
    }
}